package admin;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.common.ImageCode;
import com.common.MD5;
import com.common.ResultData;
import com.filter.BaseController;

import beans.sys.UserBean;
import service.sys.LoginServiceImpl;
import service.sys.RoleUserServiceImpl;

@Controller
@RequestMapping("/login")
public class LoginController extends BaseController {
	private Logger log = Logger.getLogger(this.getClass());

	@Resource
	private LoginServiceImpl loginServiceImpl;

	@Resource
	private RoleUserServiceImpl roleUserServiceImpl;

	@RequestMapping("/login")
	@ResponseBody
	public void login(UserBean user,String verifycode) throws IOException{
		ResultData<String> rd = new ResultData<>();
		try{
			String sessionCode = getReq().getSession().getAttribute("SESSIONCODE").toString();
			if(!sessionCode.toLowerCase().equals(verifycode.toLowerCase())){
				rd.setType(3);
				rd.setMessage("验证码不正确!");
				responseJson(rd);
				return;
			}

			String pwd = MD5.MD5Encode(user.getPassword());
			UserBean u=loginServiceImpl.Login(user.getUsername(), pwd);
			if(u != null){
				//获取用户所处角色
				List<Map> roleList = roleUserServiceImpl.getByUserid(u.getId());
				String roleids = ",";
				for(Map m : roleList) {
					roleids += m.get("roleid").toString()+",";
				}
				u.setRoles(roleids);
				getReq().getSession().setAttribute("user", u);
				rd.setSuccess(true);
			}
			else{
				rd.setType(3);
				rd.setMessage("用户名或密码不正确!");
			}
		}
		catch (Exception e) {
			rd.setType(3);
			rd.setMessage("服务器错误,请联系管理员!");
			e.printStackTrace();
		}
		responseJson(rd);
	}

	@RequestMapping("/loginout")
	@ResponseBody
	public void Loginout() throws IOException{
		getReq().getSession().setAttribute("user", null);
		getResponse().getWriter().write("1");
	}

	@RequestMapping("/VerifyCode")
	@ResponseBody
	public void VerifyCode() throws IOException{
		getResponse().setHeader("Pragma", "no-cache");
		getResponse().setHeader("Cache-Control", "no-cache");
		getResponse().setDateHeader("Expires", 0);
		getResponse().setContentType("image/jpeg");
		// 将图像输出到servlet输出流中
		ServletOutputStream sos = getResponse().getOutputStream();
		ImageCode imageCode = new ImageCode();
		ImageIO.write(imageCode.getImage(getReq()), "jpeg", sos);
		//sos.close();
	}

	@RequestMapping("/notfunction")
	public String notFunction(){
		return "common/notfunction";
	}
}